package har.mon.ix.tiltka;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;

import android.net.Uri;

public final class FileLoader {
    private final int MAX_FILE_SIZE = 500000;
    private int fileSize;
    private File file;
    private InputStream inputStream;
  
    public static FileLoader forUri(Uri uri) throws java.io.FileNotFoundException {
            return new FileLoader(uri);
    }
    
    public static FileLoader forInputStream(InputStream inputStream) throws java.io.FileNotFoundException {
        return new FileLoader(inputStream);
    }
    
    private FileLoader(InputStream inputStream) throws java.io.FileNotFoundException {
        this.inputStream = inputStream;
    }
    
    private FileLoader(Uri uri) throws java.io.FileNotFoundException {
        try {
            this.file = new File(new URI(uri.toString()));
            this.inputStream = new FileInputStream(file);
        } 
        catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }    
    }
    
    private boolean isFileSmallEnough(int fileSize) {
        if (fileSize > 0 && fileSize <= MAX_FILE_SIZE) return true;
        return false;
    }
    
    private void testFilePreLoad() throws FileLoadedTooSmallException, FileLoadedTooLargeException {
        if (fileSize == 0) { 
            throw new FileLoadedTooSmallException(fileSize);
        }  else if (!isFileSmallEnough(fileSize)) { 
            throw new FileLoadedTooLargeException(fileSize);
        }  else {
            return;
        }
    }
    
    public String assetToString() throws java.io.FileNotFoundException{
        try {
            this.fileSize = inputStream.available();
            testFilePreLoad();             
            byte[] buffer = new byte[fileSize];
            inputStream.read(buffer);
            inputStream.close();
            return new String(buffer);
        } 
        catch (IOException e) {
            throw new RuntimeException(e);
        }
        catch (FileLoadedTooSmallException e) {
            return "That file was empty so pick another one!";
        }
        catch (FileLoadedTooLargeException e) {
            return "Sorry, that file is too large: (" + e.getFileSize() + " bytes) max. size is: " + MAX_FILE_SIZE + " bytes";
        }
    }
}
